package com.guang.springbootredissondemo1;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.Resource;

/**
 * 通过看对应的RedissonAutoConfiguration发现，利用redisson可以直接来操作Redis
 * 自动配置条件@AutoConfigureBefore(RedisAutoConfiguration.class)，表示要早于RedisAutoConfiguration，直接用RedissonAutoConfiguration代替了RedisAutoConfiguration
 * 所以使用RedissonAutoConfiguration即可将之前的Redis中的依赖给去掉；
 *
 * 而且redisson的依赖还依赖了redis
 */
@Slf4j
@SpringBootApplication
public class SpringbootRedissonDemo1Application implements ApplicationRunner {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootRedissonDemo1Application.class, args);
    }

    /**
     * 直接注入RedissonClient就可以直接使用.
     */
    @Resource
    private RedissonClient redissonClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("spring boot run");

        //创建锁
        RLock helloLock = redissonClient.getLock("hello");

        //加锁
        helloLock.lock();
        try {
            log.info("locked");
            Thread.sleep(1000 * 10);
        } finally {
            //释放锁
            helloLock.unlock();
        }
        log.info("finished");
    }
}
